<template lang="pug">
  .page.h-100
    .clearfix
      .search-form.mb-10.pl-10.pr-10
        Form.ivu-row.ivu-form-basic(ref="formData" :model="formData" :rules="rules" :label-width="90")
          FormItem.form-item.ivu-col.pr-20.mb-15(v-for="(item, index) of formItem" :label="item.label" :key="index" :class="item.style" :prop="item.prop")
            template(v-if="item.type === 'select'")
              Select(v-if="item.fn" v-model="formData[item.model]" :placeholder="item.placeholder" clearable filterable @on-change="listenCall(item.fn, item.model, $event)")
                Option(
                  v-for="(c_item, index) in arrListDown[item.options]"
                  :value="c_item.value"
                  :key="index"
                ) {{ c_item.label }}
              Select(v-else v-model="formData[item.model]" :placeholder="item.placeholder" clearable filterable)
                Option(
                  v-for="(c_item, index) in arrListDown[item.options]"
                  :value="c_item.value"
                  :key="index"
                ) {{ c_item.label }}
            template(v-if="item.type === 'input'")
              Input(v-model="formData[item.model]" :placeholder="item.placeholder" clearable)
            template(v-if="item.type === 'radio'")
              RadioGroup(type="button" v-model="formData[item.model]")
                Radio.display-inline-block(v-for="c_item of item.radioArr" :label="c_item.value") {{c_item.label}}
            template(v-if="item.type === 'intervalM'")
              DatePicker.pull-left.interval-date(v-model="formData[item.model1]" :placeholder="item.placeholder1" type="month" @on-change="(val, type) => handleChangeDatePicker(val, item.model1)")
              span.pl-10.pr-10.pull-left.line-h-32 --
              DatePicker.pull-left.interval-date(v-model="formData[item.model2]" :placeholder="item.placeholder2" type="month" @on-change="(val, type) => handleChangeDatePicker(val, item.model2)")
            template(v-if="item.type === 'interval'")
              DatePicker.pull-left.interval-date(v-model="formData[item.model1]" :placeholder="item.placeholder1" type="date" @on-change="(val, type) => handleChangeDatePicker(val, item.model1)")
              span.pl-10.pr-10.pull-left.line-h-32 --
              DatePicker.pull-left.interval-date(v-model="formData[item.model2]" :placeholder="item.placeholder2" type="date" @on-change="(val, type) => handleChangeDatePicker(val, item.model2)")
            template(v-if="item.type === 'button'")
              Button(type="info" @click="searchFn") 查询

      .pl-20.pr-20.bg-white
        Table.hasTitle-table.beautiful-table(:columns="thead" :data="tableData" :stripe="true" ref="demoTable" @on-selection-change="handleOnSelectChange")
          .clearfix.font-16(slot="header")
            .table-title-lefttxt.pull-left
              |合计
              span.text-info.pl-5.pr-5.font-weight {{tableComone.totalRows}}
              |条
            .pull-right.table-title-btns
              Button.mr-10(v-if="hasExportReceivabl" type="info" @click="handleReceivabl") 导出应收单
              Button.mr-10(v-if="hasExportPayable" type="info" @click="handlePayable") 导出应付单
              Button.mr-10(v-if="hasReceive" type="info" @click="isReceiveModal" :disabled="!selectedArr.length > 0") 接收开票
              Button.mr-10(v-if="hasImportInvoice" type="info" @click="handleShowBatchImportModal") 导入
              Button.mr-10(v-if="hasBack" type="info" @click="isDeleteModal" :disabled="!selectedArr.length > 0") 驳回
              Button.mr-10(v-if="hasExportInvoice" type="info" @click="exportInvoice") 导出
              Button.mr-10(v-if="hasExportInvoice" type="info" @click="exportDetail") 导出明细
              Button(v-if="hasExportInvoice" type="info" @click="exportInvoiceBill") 导出发票台账
          .clearfix.pl-20.pr-20(slot="footer")
            Page(
              :total="tableComone.totalRows"
              @on-change="onChangePage"
              @on-page-size-change="onpageSizeChange"
              show-sizer
              show-total
              placement="top"
              prev-text="上一页"
              next-text="下一页"
              :page-size-opts="[10, 20, 30, 50, 100]"
            )
          template(slot-scope="{ row, index }" slot="action")
            Button.mr-10(v-if="hasInvoiceInfo && row.invoiceChannel != 1" type="text" size="small" @click="handleShowInvoiceApplyModal('lookModal', row.invoiceID)") 发票信息
            Button(v-if="hasInvoice && row.invoiceChannel != 1" type="text" size="small" @click="handleShowInvoiceApplyModal('makeModal', row.invoiceID)" :disabled="row.status == 3") 开票

            Button.mr-10(v-if="hasInvoiceInfo && row.invoiceChannel == 1" type="text" size="small" @click="handleShowInvoiceInstantModal('lookModal', row.invoiceID)") 发票信息
            Button(v-if="hasInvoice && row.invoiceChannel == 1 " type="text" size="small" @click="handleShowInvoiceInstantModal('makeModal', row.invoiceID)" :disabled="row.status == 3") 开票
            
            Button.mr-10(type="text" size="small" @click="gotoReceivableBillsList(row)") 应收账单
            Button.mr-10(type="text" v-if="hasAgreeBack" :disabled="row.status != 4" size="small" @click="isApprovalBackModal(row, true)") 同意退票
            Button.mr-10(type="text" v-if="hasDisagreeBack" :disabled="row.status != 4" size="small" @click="isApprovalBackModal(row, false)") 不同意退票

    //- 开票申请弹窗
    InvoiceApplyModal(ref="InvoiceApplyModal" @query="searchFn")

    //- 即时开票弹窗
    InvoiceInstantModal(ref="InvoiceInstantModal" @query="searchFn")

    //- 导入弹窗
    BatchImportModal(ref="BatchImportModal" @query="searchFn")
</template>

<script>
import { Common } from '@/utils/common.js'
import { FinanceApi } from '@/api/Finance.api.js'
import { FinanceInvoiceApi } from '@/api/FinanceInvoice.api.js'
import { InvoiceManageThead } from './tableHead.js'
import _cloneDeep from 'clone-deep'
import InvoiceApplyModal from './modal/InvoiceApplyModal.vue'
import InvoiceInstantModal from './modal/InvoiceInstantModal.vue'
import BatchImportModal from './modal/BatchImportModal.vue'

export default {
  // name: 'invoiceMake', // 开票页面

  components: {
    InvoiceApplyModal,
    InvoiceInstantModal,
    BatchImportModal
  },

  computed: {
    actionArr () {
      let arr = this.$store.state.user.actionAccess.map(item => {
        return item.code
      })
      return arr
    },
    // 查询
    hasGetFinanceInvoiceList () {
      return this.actionArr.indexOf('GetFinanceInvoiceList') > -1
    },
    // 导出
    hasExportInvoice () {
      return this.actionArr.indexOf('ExportInvoice') > -1
    },
    // 导入
    hasImportInvoice () {
      return this.actionArr.indexOf('ImportInvoice') > -1
    },
    // 开票
    hasInvoice () {
      return this.actionArr.indexOf('Invoice') > -1
    },
    // 驳回
    hasBack () {
      return this.actionArr.indexOf('Back') > -1
    },
    // 发票信息
    hasInvoiceInfo () {
      return this.actionArr.indexOf('InvoiceInfo') > -1
    },
    // 接收开票
    hasReceive () {
      return this.actionArr.indexOf('Receive') > -1
    },
    // 同意退票
    hasAgreeBack () {
      return this.actionArr.indexOf('AgreeBack') > -1
    },
    // 不同意退票
    hasDisagreeBack () {
      return this.actionArr.indexOf('DisagreeBack') > -1
    },
    // 导出应收单
    hasExportReceivabl () {
      return this.actionArr.indexOf('ExportReceivabl') > -1
    },
    // 导出应付单
    hasExportPayable () {
      return this.actionArr.indexOf('ExportPayable') > -1
    }
    
  },

  data () {
    return {
      thead: _cloneDeep(InvoiceManageThead),
      tableData: [],
      selectedId: [], // 勾选的id集合,array格式
      selectedArr: [], // 勾选的id, name数组集合
      tableComone: {
        pageIndex: 1,
        totalRows: 0,
        pageSize: 10
      },
      formData: {
        isApply: false,
        parentName: '',
        companyName: '',
        status: '',
        invoiceType: null,
        startDate: null,
        endDate: null,
        applyStartDate: null,
        applyEndDate: null,
        invoiceStartDate: null,
        invoiceEndDate: null,
        invoiceNo: '',
      },
      formItem: [
        { type: 'input', label: '集团公司：', placeholder: '请输入集团公司', prop: 'parentName', model: 'parentName', style: 'ivu-col-span-8' },
        { type: 'input', label: '客户名称：', placeholder: '请输入客户名称', prop: 'companyName', model: 'companyName', style: 'ivu-col-span-8' },
        { type: 'select', label: '开票状态：', placeholder: '请选择开票状态', prop: 'status', model: 'status', style: 'ivu-col-span-8', options: 'status' },
        { type: 'select', label: '发票类型：', placeholder: '请选择发票类型', prop: 'invoiceType', model: 'invoiceType', style: 'ivu-col-span-8', options: 'invoiceTypeList' },
        { type: 'intervalM', label: '费用月份：', placeholder1: '开始日期', prop1: 'startDate', model1: 'startDate', placeholder2: '结束日期', prop2: 'endDate', model2: 'endDate', style: 'ivu-col-span-8' },
        { type: 'interval', label: '申请时间：', placeholder1: '开始日期', prop1: 'applyStartDate', model1: 'applyStartDate', placeholder2: '结束日期', prop2: 'applyEndDate', model2: 'applyEndDate', style: 'ivu-col-span-8' },
        { type: 'interval', label: '开票时间：', placeholder1: '开始日期', prop1: 'invoiceStartDate', model1: 'invoiceStartDate', placeholder2: '结束日期', prop2: 'invoiceEndDate', model2: 'invoiceEndDate', style: 'ivu-col-span-8' },
        { type: 'input', label: '发票号码：', placeholder: '请输入发票号码', prop: 'invoiceNo', model: 'invoiceNo', style: 'ivu-col-span-8' },
        { type: 'button', style: 'ivu-col-span-8' }
      ],
      arrListDown: {
        parentCompanys: [],
        childrenCompanys: [],
        status: [],
        invoiceTypeList: [
          { label: '增值税专用发票', value: '增值税专用发票' },
          { label: '增值税普通发票', value: '增值税普通发票' },
          { label: '电子发票-普票', value: '电子发票-普票' },
        ],
      },
      rules: {}
    }
  },

  mounted () {
    this.getEnum()
    this.getParentCompanys()
    this.query()
    // approvalBackInvoice
  },

  methods: {
    // 监听所有调用的方法
    listenCall (methodsWords, ...values) {
      this[methodsWords](...values)
    },

    // 数据字典
    getEnum () {
      let groupName = 'financeinvoice.status.new'
      Common.getEnum(groupName, this.arrListDown)
    },

    // 数据字典-获取集团公司
    getParentCompanys () {
      Common.getParentCompanys(this.arrListDown, 'parentCompanys')
    },
 
    // 搜索
    searchFn () {
      this.tableComone.pageIndex = 1
      this.query()
    },

    /**
     * 分页页码变动
     * @param {Number} val pageIndex
     */
    onChangePage (val) {
      this.tableComone.pageIndex = val
      this.query()
    },
    /**
     * 分页页码变动
     * @param {Number} val pageSize
     */
    onpageSizeChange (val) {
      this.tableComone.pageIndex = 1
      this.tableComone.pageSize = val
      this.query()
    },
    /**
     * 分页查询接口
     * @param {Object} obj {pageIndex, pageSize}
     */
    async query () {
      this.selectedId = []
      this.selectedArr = []
      var params = {
        HasPaging: true,
        PageIndex: this.tableComone.pageIndex,
        PageSize: this.tableComone.pageSize
      }
      let res = await FinanceInvoiceApi.getFinanceInvoiceList({...params, ...this.formData})
      console.log('获取列表res: ', res)
      if (res.status === 200 && res.data.success) {
        this.tableData = res.data.data
        this.tableComone.totalRows = res.data.totalRows
      } else {
        this.tableData = []
      }
    },

    // 表格选择操作
    handleOnSelectChange (value) {
      this.selectedArr = value.map((item) => {
        return item
      })
      this.selectedId = value.map((item) => {
        return item.invoiceID
      })
      console.log('列表勾选数组1', this.selectedArr)
      console.log('列表勾选数组2', this.selectedId)
    },

    // 显示开票申请弹窗
    handleShowInvoiceApplyModal (modalKey, id) {
      this.$refs.InvoiceApplyModal.modalKey = modalKey
      
      switch(modalKey){
        case 'makeModal' :
          this.$refs.InvoiceApplyModal.createInvoiceModalTitle = '财务开票'
          break;
        case 'lookModal' :
          this.$refs.InvoiceApplyModal.createInvoiceModalTitle = '查看发票信息'
          break;
      }

      if (id) {
        this.$refs.InvoiceApplyModal.getModel(id)
      } else {
        this.$refs.InvoiceApplyModal.show()
      }
      this.$refs.InvoiceApplyModal.arrListDown.parentCompanys = this.arrListDown.parentCompanys
      this.$refs.InvoiceApplyModal.arrListDown.status = this.arrListDown.status
    },

    // 显示即时开票申请弹窗
    handleShowInvoiceInstantModal (modalKey, id) {
      this.$refs.InvoiceInstantModal.modalKey = modalKey
      
      switch(modalKey){
        case 'makeModal' :
          this.$refs.InvoiceInstantModal.createInvoiceModalTitle = '财务开票'
          break;
        case 'lookModal' :
          this.$refs.InvoiceInstantModal.createInvoiceModalTitle = '查看发票信息'
          break;
      }

      if (id) {
        this.$refs.InvoiceInstantModal.getModel(id)
      } else {
        this.$refs.InvoiceInstantModal.show()
      }
      // this.$refs.InvoiceInstantModal.arrListDown.parentCompanys = this.arrListDown.parentCompanys
      this.$refs.InvoiceInstantModal.arrListDown.status = this.arrListDown.status
    },

    handleShowBatchImportModal () {
      this.$refs.BatchImportModal.show()
    },

    // 获取所有集团下的公司
    parentCompanysChange (model, event) {
      if (event) {
        FinanceApi.getAllChildCompanys({companyGuid: event}).then(resp => {
          console.log('获取所有集团下的公司: ', resp)
          var arr = []
          if (resp.status === 200) {
            var costomer = resp.data.find(item => {return item.group == 'customer'})
            console.log('costomer: ', costomer)
            costomer.items.map(item => {arr.push({label: item.value, value: item.key})})
            this.arrListDown.childrenCompanys = arr
          }
        })
      }
    },

    // 是否撤回前询问
    isDeleteModal () {
      this.$Modal.confirm({
        title: '确认是否驳回开票申请！',
        onOk: () => {
          this.changeFinanceInvoice(-3)
        }
      })
    },

    // 是否接收前询问
    isReceiveModal () {
      this.$Modal.confirm({
        title: '确认是否接收开票申请！',
        onOk: () => {
          this.changeFinanceInvoice(2)
        }
      })
    },

    // 是否退票
    isApprovalBackModal (row, status) {
      this.$Modal.confirm({
        title: status?'确认是否同意退票！':'确认是否不同意退票！',
        onOk: () => {
          this.approvalBackInvoice(row, status)
        }
      })
    },
    // 退票
    async approvalBackInvoice(row, status) {
      var params = {
        invoiceID: row.invoiceID,
        Status: status
      }
      let res = await FinanceInvoiceApi.approvalBackInvoice(params)
      if (res.status === 200 && res.data.success) {
        this.$Message.success(res.data.message)
        this.query()
      } else {
        this.$Message.error({
          content: res.data.message,
          duration: 10,
          closable: true
        })
      }
    },
    
    // 确认撤回/接收
    async changeFinanceInvoice (status) {
      var params = {
        Invoices: this.selectedId,
        Status: status
      }
      let res = await FinanceInvoiceApi.changeFinanceInvoice(params)
      if (res.status === 200 && res.data.success) {
        this.$Message.success(res.data.message)
        this.query()
      } else {
        this.$Message.error({
          content: res.data.message,
          duration: 10,
          closable: true
        })
      }
    },

    // 导出发票申请
    async exportInvoice () {
      var params = {
        IDs: this.selectedId
      }
      FinanceInvoiceApi.exportInvoice({...this.formData, ...params}).then(resp => {
        console.log('导出发票申请resp: ', resp)
        if (resp.status == 200 && resp.data.success) {
          console.log('返回链接: ', resp.data.message)
          window.open(resp.data.message, '_blank')
        } else {
          this.$Message.error(resp.data.message)
        }
      })
    },

    // 导出明细
    async exportDetail () {
      var params = {
        IDs: this.selectedId
      }
      FinanceInvoiceApi.export({...this.formData, ...params}).then(resp => {
        console.log('导出明细resp: ', resp)
        if (resp.status == 200 && resp.data.success) {
          console.log('返回链接: ', resp.data.message)
          window.open(resp.data.message, '_blank')
        } else {
          this.$Message.error(resp.data.message)
        }
      })
    },

    // 导出发票台账
    async exportInvoiceBill () {
      var params = {
        IDs: this.selectedId
      }
      FinanceInvoiceApi.exportInvoiceBill({...this.formData, ...params}).then(resp => {
        console.log('导出发票台账resp: ', resp)
        if (resp.status == 200 && resp.data.success) {
          console.log('返回链接: ', resp.data.message)
          window.open(resp.data.message, '_blank')
        } else {
          this.$Message.error(resp.data.message)
        }
      })
    },

    // 日期选择
    handleChangeDatePicker (val, model) {
      this.formData[model] = val
    },

    // 去往应收账单
    gotoReceivableBillsList (row) {
      var month = row.periodMonth < 10 ? '0' + row.periodMonth : row.periodMonth
      this.$router.push({
        path: '/receivableBillsList',
        name: 'receivableBillsList',
        query: {
          serverName: row.serverName,
          companyName: row.companyName,
          date: row.periodYear + '-' + month
        }
      })
    },

    // 导出应收单
    async handleReceivabl () {
      FinanceInvoiceApi.exportReceivabl({...this.formData}).then(resp => {
        console.log('导出应收单resp: ', resp)
        if (resp.status == 200 && resp.data.success) {
          console.log('返回链接: ', resp.data.message)
          window.open(resp.data.message, '_blank')
        } else {
          this.$Message.error(resp.data.message)
        }
      })
    },

    // 导出应付单
    async handlePayable () {
      FinanceInvoiceApi.exportPayable({...this.formData}).then(resp => {
        console.log('导出应付单resp: ', resp)
        if (resp.status == 200 && resp.data.success) {
          console.log('返回链接: ', resp.data.message)
          window.open(resp.data.message, '_blank')
        } else {
          this.$Message.error(resp.data.message)
        }
      })
    },
  } // methods end
}
</script>

<style lang="less" scoped>

</style>
